package com.sunedai.tiger.service.system;

import com.sunedai.tiger.common.exception.ParamsErrorException;
import com.sunedai.tiger.dao.system.EmpUsrDao;
import com.sunedai.tiger.dao.system.entity.EmpUsr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 用户服务类
 * @author zhaolipeng
 */

@Slf4j
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class EmpUsrService {

  @Resource private EmpUsrDao empUsrDao;
  @Value("${emp.usr.login.name}") private String initEmpUsrLoginName;
  @Value("${emp.usr.password}") private String initEmpUsrPassword;

  @Transactional(rollbackFor = Exception.class)
  public EmpUsr saveOrUpdate(EmpUsr empUsr, Long loginUsrId) {
    if (empUsr.getId() == null) {
      empUsr.signPwd(empUsr.getPassword());
    }
    empUsr.setOperateUsrId(loginUsrId);
    empUsrDao.save(empUsr);
    return empUsr;
  }

  public List<EmpUsr> list(int p, int max) {
    return empUsrDao.findAll(PageRequest.of(p, max, Sort.Direction.DESC, "createDate")).getContent();
  }

  public long count() {
    return empUsrDao.count();
  }

  public EmpUsr checkLogin(String loginName, String password) {
    EmpUsr empUsr = empUsrDao.findByLoginName(loginName);
    if (empUsr == null) {
      throw ParamsErrorException.create("登录名错误");
    }
    if (!empUsr.getPassword().equals(empUsr.signPwd(password))) {
      throw ParamsErrorException.create("密码错误");
    }
    return empUsr;
  }

  @PostConstruct
  public void initSystemUsr() {
    long count = empUsrDao.count();
    if (count <= 0) {
      EmpUsr empUsr = new EmpUsr();
      empUsr.setLoginName(initEmpUsrLoginName);
      empUsr.setPassword(empUsr.signPwd(initEmpUsrPassword));
      empUsr.setOperateUsrId(1L);
      empUsr.signPwd(empUsr.getPassword());
      empUsrDao.save(empUsr);
      log.info("====初始化用户成功");
    }
  }
}
